export default {
	namespaced: true, //为当前模块开启命名空间
	state: () => {
		return {
			// 将JSON格式转换会普通格式
			cart: JSON.parse(uni.getStorageSync("cart") || "[]")
		}
	},
	mutations: {

		updateAllGoodsState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState);
			this.commit('cart_m/saveToStorage');
		},

		// 根据其goods_id删除
		removeSwipeActive(state, goods_id) {
			state.cart = state.cart.filter(item => item.goods_id !== goods_id)
			this.commit('cart_m/saveToStorage');
		},

		// 更新购物车当中的radio的状态
		updateGoodsState(state, goods) {
			// 根据goods_id查找 state cart goods_id与传递过来的goods_id一致
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id);
			if (findResult) {
				findResult.goods_state = goods.goods_state;
				// 完成持久化存储
				this.commit('cart_m/saveToStorage');
			}

		},
		addToCart(state, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id);
			if (findResult) {
				// 判断什么时候加1
				findResult.goods_count++;
			} else {
				// 什么时候添加
				state.cart.push(goods);
			}
			this.commit('cart_m/saveToStorage');
		},

		upnumChangeValue(state, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id);
			if (findResult) {
				findResult.goods_count = goods.goods_count;
				this.commit('cart_m/saveToStorage');
			}
		},
		saveToStorage(state) {
			// 永久存储，转换成JSON格式
			uni.setStorageSync("cart", JSON.stringify(state.cart))
		},


	},
	actions: {},
	getters: {

		// 总结
		changeStateMoney(state) {
			return state.cart.filter(item => item.goods_state).reduce((total, item) =>
				total += item.goods_price * item.goods_count, 0).toFixed(2)

		},

		checkedCount(state) {

			return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count, 0)

			// const filterResult = state.cart.filter(item=>item.goods_state == goods.goods_state)
			// sum = 
		},

		total(state) {
			let sum = 0;
			state.cart.forEach(goods => sum += goods.goods_count);
			return sum
		},


	}
}
